<?php
namespace app\api\controller\salesman;

use think\Controller;
use think\Request;
use think\Db;
use app\common\model\power\Rolepower;
use app\common\model\user\User as UserModel;
use app\common\model\factory\Factory as FactoryModel;
use app\api\controller\Base;
use think\facade\Env;
use app\api\controller\Pub;
class Saleman extends Base
{
    public function initialize()
    {
        parent::initialize();
        $this->is_login();
        Rolepower::powerguard('305001'); // 销售员工管理
    }

    private function is_login()
    {
        $data =UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }

    //员工列表（同一个销售组的管理员只能看到本组的员工）
    public function userList(Request $request)
    {   
        $pub=new Pub();
        $user_id=$pub->userid();
        $group_id = Db::name('user_group')->where('user_id',$user_id)->value('group_id');
        if (!$group_id) {
            return json(['code'=>0, 'msg'=>'未绑定销售组']);
        }
        $user_ids = Db::name('user_group')->where('group_id', $group_id)->column('user_id');
        $keyword = $request->get('keyword');
        $query = UserModel::whereIn('UserId', $user_ids)->where('Role',306);
        if ($keyword) {
            $query->where('Name', 'like', "%$keyword%");
        }
        $list = $query->field('UserId, Iphone, Name, Sex')->select();
        return json(['code'=>1, 'msg'=>'success', 'data'=>$list]);
    }
    
    //添加员工
    public function userAdd(Request $request)
    {
        $pub=new Pub();
        $user_id=$pub->userid();

        $group_id = Db::name('user_group')->where('user_id', $user_id)->value('group_id');
        if (!$group_id) {
            return json(['code'=>0, 'msg'=>'未绑定工厂']);
        }
        $data = $request->post();
        if (empty($data['Iphone']) || empty($data['Name']) || empty($data['sex'])) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        $user = new UserModel();
        $user->Iphone = $data['Iphone'];
        $user->Name = $data['Name'];
        $user->Sex = $data['sex'];
        $user->Role = 306; //销售组员工 
        $user->State = UserModel::STATEOK;
        $user->save();
        Db::name('user_group')->insert([
            'user_id' => $user->UserId,
            'group_id' => $group_id,
        ]);
        return json(['code'=>1, 'msg'=>'添加成功']);
    }

    //员工信息修改
    public function userEdit(Request $request)
    {
        $data = $request->post();
        if (empty($data['UserId']) || empty($data['Name']) || empty($data['Iphone']) || empty($data['sex'])) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }

        $user = UserModel::get($data['UserId']);
        if (!$user) {
            return json(['code'=>0, 'msg'=>'用户不存在']);
        }
        $user->Name = $data['Name'];
        $user->Iphone = $data['Iphone'];
        $user->Sex = $data['sex'];
        $user->save();
        return json(['code'=>1, 'msg'=>'修改成功']);
    }

    //销售员工删除
    public function userDel(Request $request)
    {
        $userId = $request->post('UserId');
        if (empty($userId)) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        Db::startTrans(); // 开启事务
        try {
            // 执行第一个数据库操作
            UserModel::destroy($userId);
            
            // 执行第二个数据库操作
            Db::name('user_group')->where('user_id', $userId)->delete();
            
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            // 返回错误信息或抛出异常
            return myerr('删除失败');
        }
        return json(['code'=>1, 'msg'=>'删除成功']);
    }

    // 代理商客户列表（只有代理商的客户，不包括销售客户）
    public function agentCustomerList()
    {
        $customerList = Db::name('user_agency')  // 用户代理商表
            ->alias('ag')
            ->join('user u', 'ag.user_id = u.UserId')  // 用户表
            ->join('user_customer uc', 'ag.user_id = uc.user_id')  // 用户客户表
            ->join('customer c', 'uc.customer_id = c.CustomerId')  // 客户表
            ->whereIn('u.Role', [303, 304])  // 查询Role为303或304的代理商
            ->field([
                'c.CustomerId' => 'customer_id',  
                'c.Name' => 'customer_name',     
                'c.AddTime' => 'customer_add_time',  
                'c.Address' => 'customer_address',  
                'UserId' => 'agent_id'  ,
                'u.Name' => 'agent_name',         
                'u.Iphone' => 'agent_phone'       
            ])
            ->select();
        return myok($customerList); 
    }

    // 销售管理将代理商的客户维护给指定员工（305001）
    public function agentCustomerToSaleCustomer()
    {
        $data=input('post.');
        if (empty($data['user_id']) || empty($data['customer_id'])) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        // 重新分配
        Db::name('user_customer')->where('customer_id', $data['customer_id'])->update(['user_id' => $data['user_id']]);
        return json(['code'=>1, 'msg'=>'分配成功']);
    }

}  